package com.jule.teenpatti.mail.service;

import JoloProtobuf.AuthSvr.JoloAuth;
import com.jule.core.jedis.StoredObjManager;
import com.jule.teenpatti.base.enums.RedisChannel;
import com.jule.teenpatti.base.enums.RedisConst;
import com.jule.teenpatti.mail.dao.DBUtil;
import com.jule.teenpatti.mail.dao.bean.MailArgsModel;
import com.jule.teenpatti.mail.dao.bean.MailAttachmentConfigModel;
import com.jule.teenpatti.mail.dao.bean.MailConfigModel;
import com.jule.teenpatti.mail.model.MailArgsMap;
import com.jule.teenpatti.mail.model.MailAttAchmentMap;
import com.jule.teenpatti.mail.model.MailConfigMap;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
@Slf4j
public class MailConfigService {
    /**
     * 加载所有配置信息
     */
    public void initConfig() {
        if (StoredObjManager.setnx(RedisConst.MAIL_CONFIG_LOADING.getProfix(),
                RedisConst.MAIL_CONFIG_LOADING.getField()) == 0L) {//两个小时内不重复加载
            return;
        }
        StoredObjManager.setEx(RedisConst.MAIL_CONFIG_LOADING.getProfix(),
                RedisConst.MAIL_CONFIG_LOADING.getField(), 60 * 60 * 2);
        //清理
        clearCache();
        //加载所有邮件配置
        loadAllMail();


    }

    /**
     * @param mailConfigId
     * @param type         1删除 0增和改
     */
    public void loadNewConfig(int mailConfigId, int type) {
        if (StoredObjManager.setnx(RedisConst.MAIL_ADD_NEW_CONFIG.getProfix(),
                RedisConst.MAIL_ADD_NEW_CONFIG.getField()) == 0L) {//15秒内不重复加载
            return;
        }
        StoredObjManager.setEx(RedisConst.MAIL_ADD_NEW_CONFIG.getProfix(),
                RedisConst.MAIL_ADD_NEW_CONFIG.getField(), 15);
        //清理掉之前遗留
        MailArgsMap mailArgsMap = getMailArgsMap();
        mailArgsMap.del(mailConfigId);
        MailConfigModel mail = null;
        if (type != 1) {
            mail = DBUtil.getMailConfigFromDbById(mailConfigId, System.currentTimeMillis());
        }
        MailConfigMap map = getMailConfigMap();
        if (mail != null) {

            map.addItem(mail);

            loadAllMailArgs(mail.getId());
            loadAllAttachment(mail.getId());
        } else {
            if (map != null) {
                map.del(mailConfigId);
            }
        }
        saveMailConfigMap(map);

        //TODO 广播给在线玩家强制刷新邮件
        StoredObjManager.publish("", RedisChannel.MAIL_NOTICE_NEW_MAIL.getChannelName());
    }

    public List<MailConfigModel> getAllMailConfig() {
        MailConfigMap map = getMailConfigMap();
        if (map == null) {
            return new ArrayList<>();
        }
        return map.getAllMailConfig();
    }

    public void saveMailConfigMap(MailConfigMap map) {
        StoredObjManager.hset(RedisConst.MAIL_CONFIG_LIST.getProfix(),
                RedisConst.MAIL_CONFIG_LIST.getField(), map);
    }

    public MailConfigMap getMailConfigMap() {
        MailConfigMap map = StoredObjManager.hget(RedisConst.MAIL_CONFIG_LIST.getProfix(),
                RedisConst.MAIL_CONFIG_LIST.getField(), MailConfigMap.class);
        return map;
    }

    private void loadAllMail() {
        List<MailConfigModel> allMail = DBUtil.getMailConfigFromDb(System.currentTimeMillis());
        MailConfigMap map = new MailConfigMap();
        if (allMail != null && allMail.size() > 0) {
            map.addItem(allMail);
            allMail.forEach(item -> {
                loadAllMailArgs(item.getId());
                loadAllAttachment(item.getId());
            });
        }
        saveMailConfigMap(map);
    }

    public MailArgsMap getMailArgsMap() {
        MailArgsMap mailArgsMap = StoredObjManager.hget(
                RedisConst.MAIL_CONFIG_ARGS.getProfix(),
                RedisConst.MAIL_CONFIG_ARGS.getField(), MailArgsMap.class);
        return mailArgsMap;
    }

    /**
     * @param mailConfigId
     */
    private void loadAllMailArgs(int mailConfigId) {
        List<MailArgsModel> allMail = DBUtil.getMailArgsConfigFromDb(mailConfigId);
        log.debug("loadAllMailArgs() mailConfigId:{},allMailArg.size:{}",mailConfigId,allMail==null?"0":allMail.size());
        if (allMail == null) {
            return;
        }
        MailArgsMap map = getMailArgsMap();

        if (map == null) {
            map = new MailArgsMap();
        }

        map.addItem(allMail);

        setMailArgsMap(map);
    }

    private void loadAllAttachment(int mailConfigId) {
        List<MailAttachmentConfigModel> allAttachment = DBUtil.getMailAttachmentFromDb(mailConfigId);
        if (allAttachment == null) {
            return;
        }
        MailAttAchmentMap map = getMailAttachmentMap();

        if (map == null) {
            map = new MailAttAchmentMap();
        }
        map.addItem(allAttachment);

        StoredObjManager.hset(RedisConst.MAIL_CONFIG_ATTACHMENT.getProfix(),
                RedisConst.MAIL_CONFIG_ATTACHMENT.getField(), map);
    }

    public List<JoloAuth.JoloAuth_MailAwardInfo> getMailAtt(int mailConfigId) {
        List<JoloAuth.JoloAuth_MailAwardInfo> list = new ArrayList<>();
        Map<Integer, MailAttachmentConfigModel> map = getMailAttMap(mailConfigId);
        if (map != null) {
            Iterator<MailAttachmentConfigModel> iter = map.values().iterator();
            while (iter.hasNext()) {
                MailAttachmentConfigModel attConfig = iter.next();
                JoloAuth.JoloAuth_MailAwardInfo.Builder att = JoloAuth.JoloAuth_MailAwardInfo.newBuilder();
                att.setName(attConfig.getName());
                att.setNum(attConfig.getNumber());
                att.setType(attConfig.getType());
                att.setUrl(attConfig.getUrl());
                att.setItemId("" + attConfig.getItem_id());
                list.add(att.build());
            }
        }
        return list;
    }

    public Map<Integer, MailAttachmentConfigModel> getMailAttMap(int mailConfigId) {
        Map<Integer, MailAttachmentConfigModel> map = getMailAttachmentMap().getAllMailArgs().get(mailConfigId);
        return map;
    }

    public MailAttAchmentMap getMailAttachmentMap() {
        MailAttAchmentMap mailAttAchmentMap = StoredObjManager.hget(
                RedisConst.MAIL_CONFIG_ATTACHMENT.getProfix(),
                RedisConst.MAIL_CONFIG_ATTACHMENT.getField(), MailAttAchmentMap.class);
        return mailAttAchmentMap;
    }

    public void setMailArgsMap(MailArgsMap map) {
        StoredObjManager.hset(RedisConst.MAIL_CONFIG_ARGS.getProfix(),
                RedisConst.MAIL_CONFIG_ARGS.getField(), map);
    }

    public void clearCache() {
        MailArgsMap map = new MailArgsMap();
        setMailArgsMap(map);
    }


    private static class SingletonHolder {
        protected static final MailConfigService instance = new MailConfigService();
    }

    public static final MailConfigService getInstance() {
        return MailConfigService.SingletonHolder.instance;
    }
}
